package com.emailTest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Component
public class SendMailBuild {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private SpringTemplateEngine templateEngine;

    //发送简单邮件
    public void sendSimpleMail(Mail mail) {
 
        //构建邮件内容对象
        //指定邮件发送者，接收者，主题，内容，发送时间
        SimpleMailMessage sendMail = new SimpleMailMessage();
        sendMail.setFrom(mail.getSendMailAccount());
        sendMail.setTo(mail.getAcceptMailAccount());
        sendMail.setSubject(mail.getTheme());
        sendMail.setText(mail.getMailText());
        sendMail.setSentDate(mail.getSendTime());
        javaMailSender.send(sendMail);
    } 
 
 
    //发送附件
    public void sendAccessoryMail(Mail mail) throws MessagingException {
        //构建邮件内容对象
        //指定邮件发送者，接收者，主题，内容，发送时间
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //mimeMessage：JavaMail 的 MimeMessage 对象，代表要发送的邮件
        //true：表示启用 multipart 模式，支持附件和HTML内容
        MimeMessageHelper sendMail = new MimeMessageHelper(mimeMessage, true);
        sendMail.setFrom(mail.getSendMailAccount());
        sendMail.setTo(mail.getAcceptMailAccount());
        sendMail.setSubject(mail.getTheme());
        sendMail.setText(mail.getMailText());
        sendMail.setSentDate(mail.getSendTime());
        //指定附件的名称和附件在你计算机中的绝对地址
        sendMail.addAttachment(mail.getAttachmentName(), new File(mail.getAttachmentPath()));
       javaMailSender.send(mimeMessage); 
   }



    //使用了Thymeleaf 作为邮件模板
    public void sendThymeleafMail(Mail mail) throws MessagingException {

        //构建邮件内容对象
        //指定邮件发送者，接收者，主题，发送时间
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //mimeMessage：JavaMail 的 MimeMessage 对象，代表要发送的邮件
        //true：表示启用 multipart 模式，支持附件和HTML内容
        MimeMessageHelper msg = new MimeMessageHelper(mimeMessage, true);
        msg.setFrom(mail.getSendMailAccount());
        msg.setTo(mail.getAcceptMailAccount());
        msg.setSubject(mail.getTheme());
        msg.setSentDate(mail.getSendTime());

        //添加模板数据
        Context context = new Context();
        mail.getstaticVars().forEach(p -> {
            context.setVariable(p.getName(), p.getValue());
        });
        //指定静态页面模板
        String process = templateEngine.process(mail.getTemplate(), context);
        msg.setText(process, true);
        javaMailSender.send(mimeMessage);
    }

}
